package com.example.shushiyunsst.fragment.main.transaction.child.content

import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.InputFilter
import android.text.Spanned
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import com.alibaba.fastjson.JSON
import com.example.library_common.base.LazyFragment
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_BALANCE_INFO
import com.example.library_common.utils.timer.BaseTimerTask
import com.example.library_common.utils.timer.ITimerListener
import com.example.library_common.view.widget_helper.RTextView
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.fragment.main.transaction.bean.TransIndexWayBean
import com.example.shushiyunsst.fragment.main.transaction.bean.TransactionUIInvokeListener
import com.example.shushiyunsst.fragment.main.transaction.bean.ValueInputFilter
import com.example.shushiyunsst.fragment.main.transaction.child.CHANG_ICON
import com.example.shushiyunsst.fragment.main.transaction.child.TRANSFER_DECIMAL_FORMAT
import com.example.shushiyunsst.fragment.main.transaction.child.TransIndexNode
import com.example.shushiyunsst.fragment.main.transaction.child.TransIndexNode.BUY
import com.example.shushiyunsst.fragment.main.transaction.child.TransIndexNode.SELL
import com.example.shushiyunsst.fragment.main.transaction.child.transfer_index_data
import com.example.shushiyunsst.util.PayingPassWordVerifyPop
import com.example.shushiyunsst.widget.ShuSiLiuIndicatorSeekBar
import com.example.wallet.bean.BalanceInfoBean
import com.example.wallet.db.BalanceInfoManager
import com.example.wallet.db.UserInfoManager
import com.example.wallet.global.AppGlobals
import com.google.android.material.textview.MaterialTextView
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.senon.modularapp.util.JssSpannableString
import com.warkiz.widget.IndicatorSeekBar
import com.warkiz.widget.OnSeekChangeListener
import com.warkiz.widget.SeekParams
import java.text.DecimalFormat
import java.util.*

/**
 * 交易设置
 * */
class TransactionSettingFragment : LazyFragment(), View.OnClickListener, TransactionSettingInvoker,
    OnSeekChangeListener, ITimerListener
{

    companion object {
        fun newInstance(): TransactionSettingFragment {
            val args = Bundle()
            val fragment = TransactionSettingFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun lazyInit() {

    }

    private var icon = ""

    private var cny = ""

    private val cnyStr = AppGlobals.getApplication().getString(R.string.wallet_cny)

    private val sstStr = AppGlobals.getApplication().getString(R.string.wallet_sst)

    private var transactionUIInvokeListener: TransactionUIInvokeListener? = null

    fun setTransactionUIInvokeListener(listener: TransactionUIInvokeListener?): TransactionSettingFragment {
        this.transactionUIInvokeListener = listener
        return this
    }

    private lateinit var moneyTv: TextView

    private lateinit var transferType: RTextView

    private lateinit var buyingTv: TextView

    private lateinit var sellTv: TextView

    private lateinit var percentageTv: TextView

    private lateinit var transactionCountTv: TextView

    private lateinit var delegation: MaterialTextView

    private lateinit var moneySelector: ImageButton

    private lateinit var iconTv: TextView

    private lateinit var availableValueTv: TextView

    private lateinit var countTv: View

    private lateinit var discount: View

    private lateinit var priceEtv: EditText

    private lateinit var assessmentTv: TextView

    private lateinit var account: EditText


    private var mTimerTask: BaseTimerTask? = null

    private var mTimer: Timer? = null

    private var timer = 15L

    private val df = DecimalFormat(TRANSFER_DECIMAL_FORMAT)

    private val handler: Handler = Handler(Looper.getMainLooper())

    private val priceEtvInputFilter = ValueInputFilter()

    private val accountInputFilter = ValueInputFilter()

    private lateinit var mShuSiLiuIndicatorSeekBar: ShuSiLiuIndicatorSeekBar

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false
    }

    override fun getLayoutId() = R.layout.transaction_setting_fragment

    @SuppressLint("SetTextI18n")
    override fun initView(view: View) {

        assessmentTv = view.findViewById(R.id.assessmentTv)

        account = view.findViewById(R.id.account)
        account.filters = arrayOf(accountInputFilter)

        priceEtv = view.findViewById(R.id.priceEtv)
        priceEtv.filters = arrayOf(priceEtvInputFilter)

        countTv = view.findViewById(R.id.countTv)

        discount = view.findViewById(R.id.discount)

        iconTv = view.findViewById(R.id.iconTv)

        mShuSiLiuIndicatorSeekBar = view.findViewById(R.id.mShuSiLiuIndicatorSeekBar)

        moneyTv = view.findViewById(R.id.moneyTv)

        transferType = view.findViewById(R.id.transferType)

        buyingTv = view.findViewById(R.id.buyingTv)

        sellTv = view.findViewById(R.id.sellTv)

        percentageTv = view.findViewById(R.id.percentageTv)

        transactionCountTv = view.findViewById(R.id.transactionCountTv)

        delegation = view.findViewById(R.id.delegation)

        moneySelector = view.findViewById(R.id.money_selector)

        availableValueTv = view.findViewById(R.id.availableValueTv)

        transactionCountTv.text = "--"

        setType()

        moneySelector.setOnClickListener(this)
        buyingTv.setOnClickListener(this)
        sellTv.setOnClickListener(this)
        countTv.setOnClickListener(this)
        discount.setOnClickListener(this)
        transferType.setOnClickListener(this)
        priceEtv.addTextChangedListener(priceEtvTextWatcher)
        account.addTextChangedListener(accountTextWatcher)
        mShuSiLiuIndicatorSeekBar.setSeekChangeListener(this)
    }


    @SuppressLint("RestrictedApi", "UseCompatTextViewDrawableApis", "SetTextI18n")
    private fun setType() {
        val transIndexNode = transactionUIInvokeListener?.getTransIndexNode()

        transIndexNode?.transType = when {
            sellTv.isSelected -> SELL
            buyingTv.isSelected -> BUY
            else -> BUY
        }

        val nowTime = System.currentTimeMillis()

        val txStartTime = (transIndexNode?.bean?.txStartTime ?: 0L)

        timer = (txStartTime - nowTime) / 1000

        if (timer <= 0) {
            transferType.text = when {
                sellTv.isSelected -> _mActivity.getString(R.string.sell_in, icon)
                buyingTv.isSelected -> _mActivity.getString(R.string.buy_in, icon)
                else -> _mActivity.getString(R.string.buy_in, icon)
            }
            transferType.helper.backgroundColorNormal =
                ContextCompat.getColor(_mActivity, R.color.PrimaryColor)
            transferType.setTextColor(ContextCompat.getColor(_mActivity, R.color.text_color_1))
            transIndexNode?.bean?.isEnableTransfer = true

        } else {
            transIndexNode?.bean?.isEnableTransfer = false
            transferType.helper.backgroundColorNormal =
                ContextCompat.getColor(_mActivity, android.R.color.transparent)
            transferType.setTextColor(ContextCompat.getColor(_mActivity, R.color.PrimaryColor))

            startTimer()

        }

        percentageTv.text = "${transIndexNode?.iconType?.updownPrice}"

        val selected = when {
            sellTv.isSelected -> true
            buyingTv.isSelected -> false
            else -> false
        }

        val colorRes = when {
            sellTv.isSelected -> R.color.image_color_red
            buyingTv.isSelected -> R.color.PrimaryColor
            else -> R.color.PrimaryColor
        }


        moneyTv.text = JssSpannableString(_mActivity, "$icon / $cny")
            .first(icon).textColor(colorRes)

        iconTv.text = icon

        if (timer <= 0) {
            transferType.isSelected = selected
        }

        percentageTv.isSelected = selected

        transactionCountTv.isSelected = selected

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            delegation.compoundDrawableTintList =
                ColorStateList.valueOf(ContextCompat.getColor(_mActivity, colorRes))

        } else {
            delegation.supportCompoundDrawablesTintList =
                ColorStateList.valueOf(ContextCompat.getColor(_mActivity, colorRes))
        }

        mShuSiLiuIndicatorSeekBar.isSelected = selected

        moneySelector.setColorFilter(ContextCompat.getColor(_mActivity, colorRes))


        val availableBalance = availableBalanceValue()

        val sslBalanceStr = df.format(availableBalance)

        availableValueTv.text = "$sslBalanceStr ${currentIconUnit()}"

        presentJaoYao()

    }

    private fun currentIconUnit(): String {
        val transIndexNode = transactionUIInvokeListener?.getTransIndexNode()
        val iconType = transIndexNode?.iconType
        return when (transIndexNode?.transType) {
            SELL ->
                iconType?.tokenName ?: ""
            BUY -> {
                iconType?.getToTransferIcon() ?: ""
            }
            else -> transIndexNode?.iconType?.getToTransferIcon() ?: ""
        }
    }

    private fun availableBalanceValue(): Double {
        val transIndexNode = transactionUIInvokeListener?.getTransIndexNode()

        return when (transIndexNode?.transType) {
            SELL -> selectValue(icon)
            BUY -> selectValue(transIndexNode.iconType?.getToTransferIcon())
            else -> selectValue(transIndexNode?.iconType?.getToTransferIcon())
        }
    }

    private fun selectValue(tokenType: String?): Double {

        val balanceInfoBean = BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()
        val balanceInfo = balanceInfoBean?.balanceInfo

        val context = AppGlobals.getApplication()

        return when (tokenType) {
            context.getString(R.string.wallet_arl) -> {
                balanceInfo?.arlBalance ?: 0.0
            }
            context.getString(R.string.wallet_cml) -> {
                balanceInfo?.cmlBalance ?: 0.0
            }
            context.getString(R.string.wallet_ssl) -> {
                balanceInfo?.sslBalance ?: 0.0
            }
            context.getString(R.string.wallet_sst) -> {
                balanceInfo?.sstBalance ?: 0.0
            }
            else -> 0.0
        }
    }

    private fun presentTime() {

        val transIndexNode = transactionUIInvokeListener?.getTransIndexNode()

        val nowTime = System.currentTimeMillis() / 1000

        val str0 = "交易时间：${transIndexNode?.bean?.dateFormatStartTime(nowTime)}"

        val str1 = "剩余时间：${timerStr()}"

        val str2 = "$str0 \n $str1"

        transferType.text =
            JssSpannableString(_mActivity, str2)
                .first(str0)
                .size(9)
                .first(str1)
                .size(9)
    }

    private fun timerStr(): String {
        val minUnit = 60
        val horUnit = 60 * 60
        val dayUnit = 60 * 60 * 24

        when {
            timer < minUnit -> {
                return "$timer 秒"
            }
            timer < horUnit -> {
                val sec = timer % minUnit
                val min = timer / minUnit
                return "$min 分 $sec 秒"
            }
            timer < dayUnit -> {
                val hor = timer / horUnit
                val min = (timer - hor * horUnit) / minUnit
                val sec = timer - hor * horUnit - min * minUnit
                return "$hor 时 $min 分 $sec 秒"
            }
            else -> {
                val day = timer / dayUnit
                val hor = (timer - day * dayUnit) / horUnit
                val min = (timer - day * dayUnit - hor * horUnit) / minUnit
                val sec = timer - day * dayUnit - hor * horUnit - min * minUnit
                return "$day 天 $hor 时 $min 分 $sec 秒"
            }
        }


    }

    override fun handMessage(msg: MessageWrap?) {
        super.handMessage(msg)
        when (msg?.message) {
            transfer_index_data, TO_REFRESH_BALANCE_INFO, CHANG_ICON -> {
                val bean = transactionUIInvokeListener?.getTransIndexNode()?.iconType
                icon = bean?.tokenName ?: ""
                cny = bean?.getToTransferIcon() ?: ""
                setType()
            }

        }

    }

    private fun startTimer() {
        if (mTimerTask !== null) return

        mTimer = Timer()

        mTimerTask = BaseTimerTask(this)

        mTimer?.schedule(mTimerTask, 0, 1000)
    }

    private fun stopTimer() {

        if (mTimer != null) {
            mTimer?.cancel()
            mTimer = null
        }

        if (mTimerTask != null) {
            mTimerTask?.cancel()
            mTimerTask = null
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        stopTimer()
        transactionUIInvokeListener = null
        priceEtv.removeTextChangedListener(priceEtvTextWatcher)
        account.removeTextChangedListener(accountTextWatcher)
        mShuSiLiuIndicatorSeekBar.setSeekChangeListener(null)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.transferType -> {
                val transIndexNode = transactionUIInvokeListener?.getTransIndexNode()
                if (transIndexNode?.bean?.isEnableTransfer == true) {
                    toTransfer()
                } else {
                    Toast.makeText(_mActivity, "未到交易时间，无法交易", Toast.LENGTH_LONG).show()
                }

            }
            R.id.countTv -> {
                val text = priceEtv.text?.toString() ?: ""
                if (text.isNotEmpty()) {
                    var value = text.toDouble()
                    val balanceInfoBean =
                        BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()
                    if (value < balanceInfoBean?.totalBalance ?: 0.0) {
                        value += 1
                        priceEtv.setText("$value")
                        priceEtv.setSelection("$value".length)
                    }
                }
            }
            R.id.discount -> {
                val text = priceEtv.text?.toString() ?: ""
                if (text.isNotEmpty()) {
                    var value = text.toDouble()
                    if (value > 0) {
                        value -= 1
                        priceEtv.setText("$value")
                        priceEtv.setSelection("$value".length)
                    }
                }
            }
            R.id.money_selector -> {
                transactionUIInvokeListener?.toggleDrawerLayout()
            }
            R.id.buyingTv -> {
                buyingTv.isSelected = true
                sellTv.isSelected = false
                sellTv.isSelected
                setType()
                transactionUIInvokeListener?.requestIndex()
            }
            R.id.sellTv -> {
                sellTv.isSelected = true
                buyingTv.isSelected = false
                setType()
                transactionUIInvokeListener?.requestIndex()
            }
        }
    }

    private fun toTransfer() {
        if (!checkInfo()) {
            return
        }


        val mPop = PayingPassWordVerifyPop(_mActivity)
        XPopup.Builder(_mActivity)
            .setPopupCallback(object : SimpleCallback() {
                override fun onDismiss(popupView: BasePopupView?) {
                    super.onDismiss(popupView)
                    if (mPop.getIsOnVerifyPop()) {
                        if (mPop.getVerifyPop()) {
                            val transType =
                                transactionUIInvokeListener?.getTransIndexNode()?.transType
                            when (transType) {
                                BUY -> {
                                    sendBuyAllData()
                                }
                                SELL -> {
                                    sendSellAllData()
                                }
                            }
                        } else {
                            Toast.makeText(_mActivity, "支付密码错误", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            })
            .asCustom(mPop)
            .show()
    }

    private fun checkInfo(): Boolean {
        var flag = true
        val txPrice = priceEtv.text.toString()
        val txPriceStr = if (txPrice.isEmpty()) 0.0 else txPrice.toDouble()
        if (txPriceStr <= 0.0) {
            flag = false
            Toast.makeText(_mActivity, "请输入价格", Toast.LENGTH_LONG).show()
        }

        val txNums = account.text.toString()
        val txNumsStr = if (txNums.isEmpty()) 0.0 else txNums.toDouble()
        if (txNumsStr <= 0.0) {
            flag = false
            Toast.makeText(_mActivity, "请输入数量", Toast.LENGTH_LONG).show()
        }

        return flag
    }

    private fun sendSellAllData() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val txPrice = df.format(priceEtv.text.toString().toDouble())
        val txNums = df.format(account.text.toString().toDouble())
        val tokenType = transactionUIInvokeListener?.getTransIndexNode()?.iconType?.tokenName

        val map = mapOf(
            "tokenType" to "$tokenType",
            "txNums" to txNums,
            "txPrice" to txPrice,
            "uid" to "${userInfo?.uid}"
        )

        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.transSell)
            .success {
                Toast.makeText(_mActivity, "发送成功", Toast.LENGTH_LONG).show()
                priceEtv.setText("")
                account.setText("")
                presentJaoYao()
                getUserBalanceInfo(_mActivity)
                transactionUIInvokeListener?.requestIndex()
            }
            .failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_LONG).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_LONG).show()
            }.build().post()
    }

    private fun sendBuyAllData() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val txPrice = df.format(priceEtv.text.toString().toDouble())
        val txNums = df.format(account.text.toString().toDouble())
        val tokenType = transactionUIInvokeListener?.getTransIndexNode()?.iconType?.tokenName

        val map = mapOf(
            "tokenType" to "$tokenType",
            "txNums" to txNums,
            "txPrice" to txPrice,
            "uid" to "${userInfo?.uid}"
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.transBuy)
            .success {
                Toast.makeText(_mActivity, "发送成功", Toast.LENGTH_LONG).show()
                priceEtv.setText("")
                account.setText("")
                presentJaoYao()
                getUserBalanceInfo(_mActivity)
                transactionUIInvokeListener?.requestIndex()
            }
            .failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_LONG).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_LONG).show()
            }.build().post()
    }

    private var priceEtvTextWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

        @SuppressLint("SetTextI18n")
        override fun afterTextChanged(s: Editable?) {

            var mStr = s?.toString()


            if (mStr?.isNotEmpty() == true) {
                val mValue = mStr.toDouble()

                val balanceInfoBean =
                    BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()

                val totalBalance=balanceInfoBean?.totalBalance ?: 0.0

                if (mValue > totalBalance) {

                    mStr = "$totalBalance"

                    priceEtv.setText("$mStr")

                    priceEtv.setSelection("$mStr".length)

                }
            }

            assessmentTv.text = "$mStr $cnyStr"

            mShuSiLiuIndicatorSeekBar.progress = 100f

            onStopTrackingTouchTv()
        }

    }

    private val accountTextWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

        @SuppressLint("SetTextI18n")
        override fun afterTextChanged(s: Editable?) {

            presentJaoYao()
        }

    }

    private fun presentJaoYao() {

        val account0 = account.text.toString()

        val accountStr =
            if (account0.isEmpty() || account0 == ".") 0.0 else account0.toDouble()

        val priceEtv0 = priceEtv.text.toString()
        val priceStr =
            if (priceEtv0.isEmpty() || priceEtv0 == ".") 0.0 else priceEtv0.toDouble()

        val transaction = accountStr * priceStr

        val transactionV = df.format(transaction)

        val transactionStr = if (transaction > 0.0) "$transactionV $sstStr" else "--"

        transactionCountTv.text = transactionStr
    }


    override fun selectCurrent(bean: TransIndexWayBean?) {

        priceEtv.setText(df.format(bean?.txPrice))

        account.setText("")

        mShuSiLiuIndicatorSeekBar.progress = 100f

        onStopTrackingTouchTv()

    }

    override fun onSeeking(seekParams: SeekParams?) {

    }

    override fun onStartTrackingTouch(seekBar: IndicatorSeekBar?) {

    }

    override fun onStopTrackingTouch(seekBar: IndicatorSeekBar?) {
        onStopTrackingTouchTv()

    }

    private fun onStopTrackingTouchTv() {
        val progress = mShuSiLiuIndicatorSeekBar.progress / 100

        val availableBalance = availableBalanceValue()

        val priceEtv0 = priceEtv.text.toString()

        val priceStr =
            if (priceEtv0.isEmpty()) 0.0 else priceEtv0.toDouble()

        var nums = 0.0

        if (priceStr > 0.0) {
            nums = (availableBalance * progress) / priceStr
        }

        val format = df.format(nums)

        account.setText(format)

        account.setSelection(format.length)

        presentJaoYao()
    }

    override fun onTimer() {

        handler.post {

            timer--

            if (timer <= 0) {

                stopTimer()

                transactionUIInvokeListener?.requestIndex()
            } else {
                presentTime()
            }

        }
    }
}